How to handle null {id} on route?

Posted by MattSlay on Stack Overflow See other posts from Stack Overflow or by MattSlay
Published on 2010-03-11T17:23:05Z Indexed on 2010/03/11 17:24 UTC
Read the original article Hit count: 226

What if a user hits my site with http://www.mysite.com/Quote/Edit rather than http://www.mysite.com/Quote/Edit/1000 In other words, they do not specify a value for {id}. If they do not, I want to display a nice "Not Found" page, since they did not give an ID. I currentl handle this by accepting a nullable int as the parameter in the Controller Action and it works fine. However, I'm curious if there a more standard MVC framework way of handling this, rather than the code I presently use (see below). Is a smoother way to handle this, or is this pretty mush the right way to do it?

    [HttpGet]
    public ActionResult Edit(int? id)
    {
        if (id == null)
            return View("QuoteNotFound");

        int quoteId = (int)id;

        var viewModel = new QuoteViewModel(this.UserId);
        viewModel.LoadQuote(quoteId);
        if (viewModel.QuoteNo > 0)
        {
            return View("Create", viewModel.Quote.Entity);
        }
        else
            return View("QuoteNotFound");
    }

© Stack Overflow or respective owner

Related posts about asp.net-mvc-routing

Related posts about asp.net-mvc